﻿using CHSystemApi.Framework.AuthServices;
using CHSystemApi.Framework.CustomType;
using CHSystemApi.Framework.Extension;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace CHSystemApi.Framework.Middleware
{
    /// <summary>
    /// 登录载荷解析中间件
    /// </summary>
    internal class LoginInfoMiddleware : IMiddleware
    {
        public RequestDelegate _next { get; set; }

        public LoginInfoMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task InvokeAsync(HttpContext httpContext)
        {
            if (httpContext.User.Claims.ToList().Count > 0)
            {
                LoginInfo loginInfo = new LoginInfo()
                {
                    uid = Convert.ToInt32(httpContext.User?.Claims?.Where(x => x.Type == "uid")?.Select(x => x.Value)?.FirstOrDefault()),
                    ip = httpContext.Request.Host.ToString(),
                    last_login_time = Convert.ToDateTime(httpContext.User?.Claims?.Where(x => x.Type == "last_login_time")?.Select(x => x.Value)?.First() ?? "0001/1/1 0:00:00"),
                    name = httpContext.User?.Claims?.Where(x => x.Type == "name")?.Select(x => x.Value)?.First() ?? "",
                    tel = httpContext.User?.Claims?.Where(x => x.Type == "tel")?.Select(x => x.Value)?.First() ?? "",
                };
                httpContext.Items.Add("LoginInfo", loginInfo);
            }
            return _next(httpContext);
        }
    }
}
